import tkinter as tk
import threading
import tkinter.messagebox as msgbox
import re
import json

def analyze_direction():
    # 修正后的分析线程（移除嵌套定义）
    def analysis_thread():
        try:
            global current_selected
            if not current_selected:
                raise ValueError("请先选择出行方向")

            # 获取用户信息
            from infos.read_write_txt import UserInfo
            name, birthday = UserInfo.read_user_info()
            
            # 获取黄历信息
            from db.mysql_db import MySQLDB
            mysql_data = MySQLDB.get_mysql_msg()
            
            # 获取当前时间
            import time
            current_time = time.strftime("%Y年%m月%d日%H:%M:%S")
            
            # 构造请求参数
            user_msg = f"{current_time}，姓名：{name}，生日：{birthday}，出行方向：{current_selected}\n黄历信息：{mysql_data}"
            print(user_msg)
            # 调用API接口
            from api.ollama_APP import get_advice_stream
            # 打开一个新的窗口来显示流式结果
            # 创建新窗口
            # 创建新窗口时修改窗口属性
            new_window = tk.Toplevel(root)
            new_window.title("分析结果")
            # 改为最大化窗口代替全屏，保留标题栏按钮
            new_window.state('zoomed')  # 替换原有的全屏设置
            # new_window.attributes("-fullscreen", True)  # 删除这行
            # new_window.geometry("800x600")  # 增大窗口尺寸
            
            # 创建主容器（占窗口宽度的90%）
            container = tk.Frame(new_window, bg=panel_bg)
            container.pack(padx=int(1000*0.05), pady=20, fill=tk.BOTH, expand=True)  # 左右各留5%间距
            
            # 创建滚动条
            scrollbar = tk.Scrollbar(container)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
            
            # 创建文本框（占容器宽度的100%）
            text_widget = tk.Text(
                container,
                wrap=tk.WORD,
                yscrollcommand=scrollbar.set,
                font=("Helvetica", 14),
                bg=panel_bg,
                fg="yellow",
                width=80  # 字符宽度（约占物理宽度的90%）
            )
            text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            
            # 配置滚动条
            scrollbar.config(command=text_widget.yview)
            
            # 打开一个新的窗口来显示流式结果
            new_window.configure(bg=panel_bg)
            # 先把user_msg显示出来
            text_widget.insert(tk.END, user_msg + "\n\n")
            text_widget.see(tk.END)
            # 创建一个框架来放置信息面板
            info_frame = tk.Frame(new_window, bg=panel_bg)
            info_frame.pack(expand=True, fill=tk.BOTH, padx=20, pady=20)
            
            # 创建一个标签来显示信息
            info_label = tk.Label(info_frame, text="信息显示面板。\n\n分析结果在此处显示\n\n耐心等待\n\n分析内容较多。",  
                                  # 恢复默认提示
                                  font=("Helvetica", 16), fg="yellow", bg=panel_bg,
                                  wraplength=200, justify=tk.LEFT)
            info_label.pack(expand=True, fill=tk.BOTH)

            # 在流式接收结果处增加处理逻辑（约39-45行）
            full_result = ""
            list = get_advice_stream(user_msg)
            for chunk in list:
                full_result += chunk
                new_window.after(0, text_widget.insert, tk.END, chunk)
                new_window.after(0, text_widget.see, tk.END)
            
            # 新增：等待所有数据接收完成后再处理JSON
            try:
                # 使用更宽松的正则匹配模式
                full_result = full_result.replace('\u3000', '').replace('\xa0', '').replace('\n', '').replace('\r', '').replace('\t', '').replace(' ', '')
                json_match = re.search(r'(\{.*?\})', full_result, re.DOTALL)
                if not json_match:
                    print("未找到有效JSON数据，原始响应：", full_result)
                    return  # 直接返回不处理
                
                json_str = json_match.group(1).strip()
                # 增强容错处理
                json_str = re.sub(r'[\u200b\u200c\u200d\ufeff]', '', json_str)  # 去除特殊Unicode字符
                
                # 尝试解析JSON
                result = json.loads(json_str)
                
                new_window.after(0, lambda: luck_label.config(
                    text=result["eight_meaning"],
                    fg="#FF4500" if result["eight_meaning"] == "凶" else "#ffcf00"
                ))
                # 解析完毕后将json数据按照:询问时间 询问方向 吉凶 三项来存储到./infos/listHistory.txt中
                from infos.read_write_txt import UserInfo
                # 写入历史记录
                # 确保在保存历史记录时字段顺序正确
                UserInfo.write_history_info(
                    f"{current_time}→{result['eight_type']}→{result['eight_meaning']}"
                    f"→{result['eight_analysis']}→{result['eight_advice']}"
                )
                print("写入成功。")
            except Exception as e:
                # 添加默认参数捕获异常对象
                new_window.after(0, lambda e=e: msgbox.showerror("JSON解析错误", str(e)))
                print("JSON解析错误:", e)
        except Exception as e:
            # 同步修正此处异常处理
            new_window.after(0, lambda e=e: msgbox.showerror("错误", str(e)))
            print("发生错误:", e)
    # 确保线程正常启动（原错误位于嵌套结构中）
    threading.Thread(target=analysis_thread, daemon=True).start()

root = tk.Tk()
root.title("出行方向运势分析")
root.geometry("800x600")
root.configure(bg="#3E5C76")

# 设置左右边距
side_margin = 30

# 创建一个框架来包含方向按钮，设置左右边距
button_frame = tk.Frame(root, bg="#3E5C76")
button_frame.pack(pady=20, padx=(side_margin, side_margin))

directions = ["西北", "正北", "东北",
              "正西", "开始分析", "正东",
              "西南", "正南", "东南"]

# 放置方向按钮
# 修改按钮创建部分（约34-47行）
for i in range(9):
    row = i // 3
    col = i % 3
    text = directions[i]
    
    # 创建基础按钮样式
    btn = tk.Button(button_frame, text=text, font=("Helvetica", 36),
                   fg="yellow", borderwidth=3, relief=tk.RAISED)
    
    # 设置不同按钮样式
    if text == "开始分析":
        btn.configure(bg="#2F657A", command=analyze_direction)
    else:
        # 修改全局函数名称（约54-65行）
        def update_button_color(selected_text):
            global current_selected
            # 恢复所有按钮颜色
            for child in button_frame.winfo_children():
                if child["text"] != "开始分析":
                    child.config(bg="#3E5C76", fg="yellow")  # 新增文字颜色恢复
            
            # 设置新选中按钮样式
            if selected_text != "开始分析" and selected_text != current_selected:
                for child in button_frame.winfo_children():
                    if child["text"] == selected_text:
                        # 同时修改背景和文字颜色
                        child.config(bg="white", fg="#3E5C76")
                        current_selected = selected_text
        
        # 修改按钮命令绑定（约44行）
        btn.configure(bg="#3E5C76", 
                     command=lambda t=text: update_button_color(t))  # 同步修改函数名
    
    btn.grid(row=row, column=col, padx=10, pady=10)

# 添加全局状态跟踪变量
current_selected = None

def update_button_state(selected_text):
    global current_selected
    # 恢复所有方位按钮颜色
    for child in button_frame.winfo_children():
        if child["text"] != "开始分析":
            child.config(bg="#3E5C76")
    
    # 设置新选中按钮颜色
    if selected_text != "开始分析" and selected_text != current_selected:
        for child in button_frame.winfo_children():
            if child["text"] == selected_text:
                child.config(bg="white")
                current_selected = selected_text

# 创建一个框架来包含下方三个面板，设置左右边距
bottom_frame = tk.Frame(root, bg="#3E5C76")
bottom_frame.pack(pady=20, padx=(side_margin, side_margin))

# 定义下方面板的背景颜色
panel_bg = "#2F657A"

# 使用方法说明
usage_frame = tk.Frame(bottom_frame, bg=panel_bg)
usage_frame.pack(side=tk.LEFT, padx=10, fill=tk.BOTH, expand=True)
usage_label = tk.Label(usage_frame, text="使用方法: 选中要出行的方向后点击中央部分的开始分析按钮即可。",
                       font=("Helvetica", 16), fg="yellow", bg=panel_bg, wraplength=200)
usage_label.pack(pady=10, padx=10)

# 结果显示区域
result_frame = tk.Frame(bottom_frame, bg=panel_bg)
result_frame.pack(side=tk.LEFT, padx=10, fill=tk.BOTH, expand=True)

# 单独创建吉凶显示控件
luck_label = tk.Label(result_frame, text="吉/凶", 
                     font=("Helvetica", 27, "bold"),  # 加大字号并加粗
                     fg="#ffcf00", bg=panel_bg)
luck_label.pack(pady=5)

# 信息显示面板
info_frame = tk.Frame(bottom_frame, bg=panel_bg)
info_frame.pack(side=tk.LEFT, padx=10, fill=tk.BOTH, expand=True)
# 修改信息面板初始化（约87行）
info_label = tk.Label(info_frame, text="根据您的生辰与今日黄历日期共同分析结果会在新窗口显示，由于分析内容较多，需要适当等待。",  # 初始为空
                      font=("Helvetica", 16), fg="yellow", bg=panel_bg, 
                      wraplength=200, justify=tk.LEFT)
info_label.pack(pady=10, padx=10)

# 修改主窗口创建方式为继承Toplevel
class AnalysisWindow(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        # 获取父窗口位置尺寸
        x = parent.winfo_x()+1300
        y = parent.winfo_y()+500
        width = parent.winfo_width()
        height = parent.winfo_height()
        
        # 设置与父窗口完全一致的几何属性
        self.geometry(f"{width}x{height}+{x}+{y}")
        self.title("AI出行分析")
        self.configure(bg="#3E5C76")
        
        self.create_widgets()
        
        # 添加窗口置顶属性
        self.attributes('-topmost', 1)
        self.after(100, lambda: self.attributes('-topmost', 0))  # 置顶后恢复

# 在class AnalysisWindow中添加以下方法
def create_direction_buttons(self):
    self.selected_button = None  # 跟踪当前选中按钮
    directions = ["西北", "正北", "东北", "正西", "开始分析", "正东", "西南", "正南", "东南"]
    
    for i in range(9):
        row = i // 3
        col = i % 3
        text = directions[i]
        
        btn = tk.Button(self.button_frame, text=text, font=("Helvetica", 24),
                       fg="yellow", bg="#3E5C76", relief=tk.RAISED,
                       command=lambda t=text: self.update_button_state(t))
        
        if text == "开始分析":
            btn.configure(bg="#2F657A", command=self.analyze_direction)
        else:
            btn.bind("<Button-1>", lambda e, t=text: self.update_button_state(t))
        
        btn.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")

def update_button_state(self, direction):
    # 恢复所有按钮状态
    for child in self.button_frame.winfo_children():
        if isinstance(child, tk.Button) and child["text"] != "开始分析":
            child.config(relief=tk.RAISED)
    
    # 设置当前按钮状态
    if direction != "开始分析":
        for child in self.button_frame.winfo_children():
            if child["text"] == direction:
                child.config(relief=tk.SUNKEN)
                self.selected_button = direction

root.mainloop()
    